pub trait FromData: Sized {
	const SIZE: usize;
	fn parse(data: &[u8]) -> Option<Self>;
}
pub trait FromSlice<'a>: Sized {
	/// Parses an object from a raw data.
	fn parse(data: &'a [u8]) -> Option<Self>;
}

/// A streaming binary parser.
#[derive(Clone, Default, Debug)]
pub struct Stream<'a> {
	data: &'a [u8],
	offset: usize,
}
impl<'a> Stream<'a> {
	#[inline]
	pub fn new(data: &'a [u8]) -> Self {
		Stream { data, offset: 0 }
	}
	#[inline]
	pub fn new_at(data: &'a [u8], offset: usize) -> Option<Self> {
		if offset <= data.len() {
			Some(Stream { data, offset })
		} else {
			None
		}
	}

	#[inline]
	pub fn data(&self) -> &'a [u8] {
		self.data
	}
	#[inline]
	pub fn offset(&self) -> usize {
		self.offset
	}
	#[inline]
	pub fn at_end(&self) -> bool {
		self.offset >= self.data.len()
	}

	#[inline]
	pub fn seek(&mut self, offset: usize) {
		self.offset = offset;
	}
	#[inline]
	pub fn seek_to_end(&mut self) {
		self.seek(self.data.len());
	}
	#[inline]
	pub fn advance(&mut self, len: usize) {
		self.offset += len;
	}
	#[inline]
	pub fn advance_checked(&mut self, len: usize) -> Option<()> {
		if self.offset + len <= self.data.len() {
			self.advance(len);
			Some(())
		} else {
			None
		}
	}

	#[inline]
	pub fn tail(&self) -> Option<&'a [u8]> {
		self.data.get(self.offset..)
	}
	#[inline]
	pub fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
		debug_assert!(self.offset as u64 + len as u64 <= u32::MAX as u64);
		let v = self.data.get(self.offset..self.offset + len)?;
		self.advance(len);
		Some(v)
	}
	#[inline]
	pub fn peek_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
		debug_assert!(self.offset as u64 + len as u64 <= u32::MAX as u64);
		let v = self.data.get(self.offset..self.offset + len)?;
		Some(v)
	}

	#[inline]
	pub fn jump_to_end(&mut self) {
		self.offset = self.data.len();
	}
	#[inline]
	pub fn skip<T: FromData>(&mut self) {
		self.advance(T::SIZE);
	}
	#[inline]
	pub fn read<T: FromData>(&mut self) -> Option<T> {
		self.read_bytes(T::SIZE).and_then(T::parse)
	}
	#[inline]
	pub fn peek<T: FromData>(&mut self) -> Option<T> {
		self.peek_bytes(T::SIZE).and_then(T::parse)
	}
	#[inline]
	pub fn read_at<T: FromData>(data: &[u8], offset: usize) -> Option<T> {
		data.get(offset..offset + T::SIZE).and_then(T::parse)
	}

	#[inline]
	pub fn parse_array16<T: FromData>(&mut self) -> Option<LazyArray16<'a, T>> {
		let count: u16 = self.read()?;
		self.read_array16(count)
	}
	#[inline]
	pub fn read_array16<T: FromData>(&mut self, count: u16) -> Option<LazyArray16<'a, T>> {
		let len = usize::from(count) * T::SIZE;
		self.read_bytes(len).map(LazyArray16::new)
	}
	#[inline]
	pub fn parse_array32<T: FromData>(&mut self) -> Option<LazyArray32<'a, T>> {
		let count: u32 = self.read()?;
		self.read_array32(count)
	}
	#[inline]
	pub fn read_array32<T: FromData>(&mut self, count: u32) -> Option<LazyArray32<'a, T>> {
		let len = count as usize * T::SIZE;
		self.read_bytes(len).map(LazyArray32::new)
	}
}

impl FromData for () {
	const SIZE: usize = 0;
	#[inline]
	fn parse(_: &[u8]) -> Option<Self> {
		Some(())
	}
}
impl FromData for u8 {
	const SIZE: usize = 1;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.get(0).copied()
	}
}
impl FromData for i8 {
	const SIZE: usize = 1;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.get(0).copied().map(|n| n as i8)
	}
}
impl FromData for u16 {
	const SIZE: usize = 2;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.try_into().ok().map(u16::from_be_bytes)
	}
}
impl FromData for i16 {
	const SIZE: usize = 2;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.try_into().ok().map(i16::from_be_bytes)
	}
}
impl FromData for u32 {
	const SIZE: usize = 4;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.try_into().ok().map(u32::from_be_bytes)
	}
}
impl FromData for i32 {
	const SIZE: usize = 4;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.try_into().ok().map(i32::from_be_bytes)
	}
}
impl FromData for u64 {
	const SIZE: usize = 8;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.try_into().ok().map(u64::from_be_bytes)
	}
}
impl FromData for i64 {
	const SIZE: usize = 8;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		data.try_into().ok().map(i64::from_be_bytes)
	}
}

#[derive(Clone, Copy)]
pub struct LazyArray16<'a, T> {
	data: &'a [u8],
	data_type: core::marker::PhantomData<T>,
}
impl<'a, T: FromData> LazyArray16<'a, T> {
	#[inline]
	pub fn new(data: &'a [u8]) -> Self {
		LazyArray16 {
			data,
			data_type: core::marker::PhantomData,
		}
	}
	#[inline]
	pub fn get(&self, index: u16) -> Option<T> {
		if index < self.len() {
			let start = usize::from(index) * T::SIZE;
			let end = start + T::SIZE;
			self.data.get(start..end).and_then(T::parse)
		} else {
			None
		}
	}
	#[inline]
	pub fn last(&self) -> Option<T> {
		if !self.is_empty() {
			self.get(self.len() - 1)
		} else {
			None
		}
	}
	#[inline]
	pub fn len(&self) -> u16 {
		(self.data.len() / T::SIZE) as u16
	}
	#[inline]
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}
	#[inline]
	pub fn slice(&self, range: core::ops::Range<u16>) -> Option<Self> {
		let start = usize::from(range.start) * T::SIZE;
		let end = usize::from(range.end) * T::SIZE;
		Some(LazyArray16 {
			data: self.data.get(start..end)?,
			..LazyArray16::default()
		})
	}
	/// Performs a binary search by specified `key`.
	#[inline]
	pub fn binary_search(&self, key: &T) -> Option<(u16, T)>
	where
		T: Ord,
	{
		self.binary_search_by(|p| p.cmp(key))
	}
	/// Performs a binary search using specified closure.
	#[inline]
	pub fn binary_search_by<F>(&self, mut f: F) -> Option<(u16, T)>
	where
		F: FnMut(&T) -> core::cmp::Ordering,
	{
		// Based on Rust std implementation.
		use core::cmp::Ordering;
		let mut size = self.len();
		if size == 0 {
			return None;
		}
		let mut base = 0;
		while size > 1 {
			let half = size / 2;
			let mid = base + half;
			// mid is always in [0, size), that means mid is >= 0 and < size.
			// mid >= 0: by definition
			// mid < size: mid = size / 2 + size / 4 + size / 8 ...
			let cmp = f(&self.get(mid)?);
			base = if cmp == Ordering::Greater { base } else { mid };
			size -= half;
		}
		// base is always in [0, size) because base <= mid.
		let value = self.get(base)?;
		if f(&value) == Ordering::Equal {
			Some((base, value))
		} else {
			None
		}
	}
}
impl<T> Default for LazyArray16<'_, T> {
	#[inline]
	fn default() -> Self {
		LazyArray16 {
			data: &[],
			data_type: core::marker::PhantomData,
		}
	}
}
impl<'a, T: FromData + core::fmt::Debug + Copy> core::fmt::Debug for LazyArray16<'a, T> {
	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
		f.debug_list().entries(*self).finish()
	}
}
impl<'a, T: FromData> FromSlice<'a> for LazyArray16<'a, T> {
	fn parse(data: &'a [u8]) -> Option<Self> {
		Stream::new(data).parse_array16()
	}
}
impl<'a, T: FromData> IntoIterator for LazyArray16<'a, T> {
	type Item = T;
	type IntoIter = LazyArrayIter16<'a, T>;
	#[inline]
	fn into_iter(self) -> Self::IntoIter {
		LazyArrayIter16 { data: self, index: 0 }
	}
}
#[derive(Clone, Copy)]
pub struct LazyArrayIter16<'a, T> {
	data: LazyArray16<'a, T>,
	index: u16,
}
impl<'a, T: FromData> Iterator for LazyArrayIter16<'a, T> {
	type Item = T;
	#[inline]
	fn next(&mut self) -> Option<Self::Item> {
		self.index += 1; // TODO: check
		self.data.get(self.index - 1)
	}

	#[inline]
	fn count(self) -> usize {
		usize::from(self.data.len().saturating_sub(self.index))
	}
}

#[derive(Clone, Copy)]
pub struct LazyArray32<'a, T> {
	data: &'a [u8],
	data_type: core::marker::PhantomData<T>,
}
impl<'a, T: FromData> LazyArray32<'a, T> {
	#[inline]
	pub fn new(data: &'a [u8]) -> Self {
		LazyArray32 {
			data,
			data_type: core::marker::PhantomData,
		}
	}
	#[inline]
	pub fn get(&self, index: u32) -> Option<T> {
		if index < self.len() {
			let start = index as usize * T::SIZE;
			let end = start + T::SIZE;
			self.data.get(start..end).and_then(T::parse)
		} else {
			None
		}
	}
	#[inline]
	pub fn last(&self) -> Option<T> {
		if !self.is_empty() {
			self.get(self.len() - 1)
		} else {
			None
		}
	}
	#[inline]
	pub fn len(&self) -> u32 {
		(self.data.len() / T::SIZE) as u32
	}
	#[inline]
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}
	/// Performs a binary search by specified `key`.
	#[inline]
	pub fn binary_search(&self, key: &T) -> Option<(u32, T)>
	where
		T: Ord,
	{
		self.binary_search_by(|p| p.cmp(key))
	}
	/// Performs a binary search using specified closure.
	#[inline]
	pub fn binary_search_by<F>(&self, mut f: F) -> Option<(u32, T)>
	where
		F: FnMut(&T) -> core::cmp::Ordering,
	{
		// Based on Rust std implementation.

		use core::cmp::Ordering;

		let mut size = self.len();
		if size == 0 {
			return None;
		}

		let mut base = 0;
		while size > 1 {
			let half = size / 2;
			let mid = base + half;
			// mid is always in [0, size), that means mid is >= 0 and < size.
			// mid >= 0: by definition
			// mid < size: mid = size / 2 + size / 4 + size / 8 ...
			let cmp = f(&self.get(mid)?);
			base = if cmp == Ordering::Greater { base } else { mid };
			size -= half;
		}

		// base is always in [0, size) because base <= mid.
		let value = self.get(base)?;
		if f(&value) == Ordering::Equal {
			Some((base, value))
		} else {
			None
		}
	}
}
impl<T> Default for LazyArray32<'_, T> {
	#[inline]
	fn default() -> Self {
		LazyArray32 {
			data: &[],
			data_type: core::marker::PhantomData,
		}
	}
}
impl<'a, T: FromData + core::fmt::Debug + Copy> core::fmt::Debug for LazyArray32<'a, T> {
	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
		f.debug_list().entries(*self).finish()
	}
}
impl<'a, T: FromData> FromSlice<'a> for LazyArray32<'a, T> {
	fn parse(data: &'a [u8]) -> Option<Self> {
		Stream::new(data).parse_array32()
	}
}
impl<'a, T: FromData> IntoIterator for LazyArray32<'a, T> {
	type Item = T;
	type IntoIter = LazyArrayIter32<'a, T>;
	#[inline]
	fn into_iter(self) -> Self::IntoIter {
		LazyArrayIter32 { data: self, index: 0 }
	}
}
#[derive(Clone, Copy)]
#[allow(missing_debug_implementations)]
pub struct LazyArrayIter32<'a, T> {
	data: LazyArray32<'a, T>,
	index: u32,
}
impl<'a, T: FromData> Iterator for LazyArrayIter32<'a, T> {
	type Item = T;
	#[inline]
	fn next(&mut self) -> Option<Self::Item> {
		self.index += 1; // TODO: check
		self.data.get(self.index - 1)
	}
	#[inline]
	fn count(self) -> usize {
		self.data.len().saturating_sub(self.index) as usize
	}
}

/// A safe u32 to usize casting.
///
/// Rust doesn't implement `From<u32> for usize`,
/// because it has to support 16 bit targets.
/// We don't, so we can allow this.
pub trait NumFrom<T>: Sized {
	/// Converts u32 into usize.
	fn num_from(_: T) -> Self;
}
impl NumFrom<u32> for usize {
	#[inline]
	fn num_from(v: u32) -> Self {
		#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
		{
			v as usize
		}
		// compilation error on 16 bit targets
	}
}
impl NumFrom<char> for usize {
	#[inline]
	fn num_from(v: char) -> Self {
		#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
		{
			v as usize
		}
		// compilation error on 16 bit targets
	}
}

/// Just like TryFrom<N>, but for numeric types not supported by the Rust's std.
pub trait TryNumFrom<T>: Sized {
	/// Casts between numeric types.
	fn try_num_from(_: T) -> Option<Self>;
}
impl TryNumFrom<f32> for u8 {
	#[inline]
	fn try_num_from(v: f32) -> Option<Self> {
		i32::try_num_from(v).and_then(|v| u8::try_from(v).ok())
	}
}
impl TryNumFrom<f32> for i16 {
	#[inline]
	fn try_num_from(v: f32) -> Option<Self> {
		i32::try_num_from(v).and_then(|v| i16::try_from(v).ok())
	}
}
impl TryNumFrom<f32> for u16 {
	#[inline]
	fn try_num_from(v: f32) -> Option<Self> {
		i32::try_num_from(v).and_then(|v| u16::try_from(v).ok())
	}
}
#[allow(clippy::manual_range_contains)]
impl TryNumFrom<f32> for i32 {
	#[inline]
	fn try_num_from(v: f32) -> Option<Self> {
		// Based on https://github.com/rust-num/num-traits/blob/master/src/cast.rs

		// Float as int truncates toward zero, so we want to allow values
		// in the exclusive range `(MIN-1, MAX+1)`.

		// We can't represent `MIN-1` exactly, but there's no fractional part
		// at this magnitude, so we can just use a `MIN` inclusive boundary.
		const MIN: f32 = i32::MIN as f32;
		// We can't represent `MAX` exactly, but it will round up to exactly
		// `MAX+1` (a power of two) when we cast it.
		const MAX_P1: f32 = i32::MAX as f32;
		if v >= MIN && v < MAX_P1 {
			Some(v as i32)
		} else {
			None
		}
	}
}
